package com.lin.shiro;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.Realm;

import java.util.Collection;
import java.util.HashMap;

/**
 * @author 霖霖
 * @version 1.0
 * @date 2023/3/29 11:44
 * @Description 多Realm
 */
public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {

        assertRealmsConfigured();

        Collection<Realm> realms = getRealms();

        HashMap<String, Realm> realmHashMap = new HashMap<>();
        JWTToken token = (JWTToken) authenticationToken;

        if (StringUtils.isEmpty(token.getLoginType()))
            throw new UnauthenticatedException("缺少认证类型");
        for (Realm realm : realms) {
            if (realm.getName().contains(token.getLoginType())){
                realmHashMap.put(token.getLoginType(),realm);
            }
        }


        return doSingleRealmAuthentication(realmHashMap.get(token.getLoginType()), token);
    }
}
